<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )

  edit-form(
    v-bind="editFormProps"
  )
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type EditFormProps,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { type QueryPagination, useApi } from "@scmt/core-api";
import type {
  PortfolioProjectEntity,
  PortfolioProjectQueryParams,
} from "@scmt/api-lis-portfolio-project";
import { useRequest } from "@scmt/common-hooks";

const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<PortfolioProjectQueryParams>({
  pageNum: 1,
  pageSize: 20,
});
const editingObj = ref<null | PortfolioProjectEntity>(null);

const selectEquipment = defineModel();

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    return $api.lis.portfolioProject.query(params);
  },
  save: (model: PortfolioProjectEntity) => {
    return $api.lis.portfolioProject.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageNum: 1,
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.lis.portfolioProject.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  listAsOptions: () => {
    return $api.lis.tube.listAsOptions();
  },
  listcategoryOptions: () => {
    return $api.lis.specimen.category.listAsOptions();
  },
  listinspectAsOptions: () => $api.lis.inspectGroup.listAsOptions(),
  loadcollectionMethod: () => $api.dict.item.listAsOptions("collection_method"),
});

onMounted(() => {
  request("tableData");
  request("listAsOptions");
  request("listcategoryOptions");
  request("listinspectAsOptions");
  request("loadcollectionMethod");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "name",
      label: "项目名称",
    },
  ];

  const headerActions: Action[] = ["add"];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    columns: 2,
    onAct: onPageActions,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "index",
        label: "序号",
        width: "60px",
      },
      {
        prop: "name",
        label: "项目名称",
      },
      {
        prop: "tubeId",
        label: "关联试管",
        width: 130,
        render: ({ row }) => {
          let resText = row.tubeId;
          return h(
            "div",
            {
              style: {
                width: "100%",
                textAlign: "center",
              },
            },
            resText
          );
        },
      },
      {
        prop: "specimenTypeId",
        label: "关联标本",
        render: ({ row }) => {
          const patientType = data.listcategoryOptions ?? [];
          let resText = row.specimenTypeId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.specimenTypeId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "collectionMethod",
        label: "采集方式",
        render: ({ row }) => {
          const patientType = data.loadcollectionMethod ?? [];
          let resText = row.collectionMethod;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.collectionMethod
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },

      {
        prop: "inspectionTeam",
        label: "检验小组",
        render: ({ row }) => {
          const patientType = data.listinspectAsOptions ?? [];
          let resText = row.inspectionTeam;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.inspectionTeam
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "reportFormat",
        label: "检验周期",
      },
      {
        prop: "whether",
        label: "是否启用",
        render: (params) => {
          return h(resolveComponent("mt-switch"), {
            modelValue: params.row.whether == 1 ? true : false,
          });
        },
      },
      {
        label: "操作",
        actions: ["edit", "destroy"],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    highlightCurrentRow: true,
    cellStyle: ({ row, column }) => {
      if (column.property === "tubeId") {
        return {
          background: `${row.tubeColor}!important`,
          // color: "var(--el-color-white)",
        };
      }
    },
    onRowClick: (row: any) => {
      selectEquipment.value = row;
    },
  };
  return tableProps;
});

const editFormProps = computed<EditFormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "name",
      label: "项目名称",
      required: true,
    },
    {
      prop: "code",
      label: "项目编码",
    },
    {
      prop: "price",
      label: "项目价格",
      required: false,
      options: {
        appendText: "元",
      },
    },
    {
      prop: "templateId",
      label: "报告模板",
      required: false,
      as: "select",
      options: {
        loadMethod: () =>
          $api.bdm.template.listAsOptionsOffice({
            officeId: "1818554809192681472",
          }),
      },
    },
    {
      prop: "combinedId",
      label: "关联试管",
      as: "select",
      options: {
        loadMethod: () => $api.lis.tube.listAsOptions(),
        onSelect: (row: any) => {
          Object.assign(editingObj.value, {
            specimenTypeId: row._raw.specimenTypeId,
            collectionMethod: row._raw.collectionMethod,
          });
        },
      },
    },
    {
      prop: "specimenTypeId",
      label: "关联标本",
      as: "select",
      disabled: true,
      options: {
        loadMethod: () => $api.lis.specimen.category.listAsOptions(),
      },
    },

    {
      prop: "collectionMethod",
      label: "采集方式",
      as: "select",
      disabled: true,
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("collection_method"),
      },
    },
    {
      prop: "inspectionTeam",
      label: "检验小组",
      as: "select",
      options: {
        loadMethod: () => $api.lis.inspectGroup.listAsOptions(),
      },
    },
    {
      prop: "reportFormat",
      label: "检验周期",
    },
    {
      prop: "whether",
      label: "是否启用",
      as: "switch",
      options: {
        activeValue: 1,
        inactiveValue: 0,
      },
    },
    {
      prop: "outward",
      label: "是否外送",
      as: "switch",
      options: {
        activeValue: 1,
        inactiveValue: 0,
      },
    },
  ];

  const editProps: EditFormProps = {
    model: editingObj.value,
    items: formItems,
    loading: loadingMap.save,
    columns: 2,
    size: "middle",
    onClose: () => {
      editingObj.value = null;
    },
    onCancel: () => {
      editingObj.value = null;
    },
    onValidate: (model) => {
      request("save", model);
    },
  };

  return editProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.lis.portfolioProject.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");

      break;
  }
};
</script>

<style lang="less" scoped></style>
